<?php

namespace App\Console\Commands\Cruise;

use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckRectifyModel;
use App\Models\Cruise\CruiseCheckTaskModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseTemplateModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class RefreshCruiseCheckTemplateType extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:refresh-templateType';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '刷新稽核表新增templateType';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        CruiseCheckTaskModel::query()->where('templateType', 0)->get()->each(function ($item) {
            $item->templateType = $this->byTemplateId($item->templateId);
            $item->save();

            $this->info("CruiseCheckTaskModel id:{$item->id} templateType:{$item->templateType}");
        });

        CruiseCheckRectifyModel::query()->where('templateType', 0)->get()->each(function ($item) {
            $item->templateType = $this->byCruiseOrderId($item->cruiseOrderId);
            $item->save();

            $this->info("CruiseCheckRectifyModel id:{$item->id} templateType:{$item->templateType}");
        });

        CruiseCheckDetailModel::query()->where('templateType', 0)->get()->each(function ($item) {
            $item->templateType = $this->byCruiseOrderId($item->orderId);
            $item->save();

            $this->info("CruiseCheckDetailModel id:{$item->id} templateType:{$item->templateType}");
        });
    }

    private function byTemplateId(int $templateId)
    {
        $templateType = Cache::store('array')
                             ->remember('byTemplateId:' . $templateId, 120, function () use ($templateId) {
                                 return CruiseTemplateModel::query()->where('id', $templateId)
                                                           ->value('type');
                             });

        return $templateType ?: CruiseTemplateModel::TYPE_3;
    }

    private function byCruiseOrderId(int $cruiseOrderId)
    {
        $templateType = Cache::store('array')
                             ->remember('byCruiseOrderId:' . $cruiseOrderId, 120, function () use ($cruiseOrderId) {
                                 return CruiseOrderModel::query()->where('id', $cruiseOrderId)->value('type');
                             });

        return $templateType ?: CruiseTemplateModel::TYPE_3;

    }
}
